const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 静态文件服务
app.use(express.static(__dirname));

// 路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

// 黑名单数据API
app.get('/api/blacklist', (req, res) => {
    try {
        const dataPath = path.join(__dirname, 'data', 'blacklist.json');
        if (fs.existsSync(dataPath)) {
            const data = fs.readFileSync(dataPath, 'utf8');
            res.json(JSON.parse(data));
        } else {
            res.json([]);
        }
    } catch (error) {
        console.error('读取黑名单数据失败:', error);
        res.status(500).json({ error: '读取数据失败' });
    }
});

app.post('/api/blacklist', (req, res) => {
    try {
        const dataPath = path.join(__dirname, 'data', 'blacklist.json');
        const dataDir = path.dirname(dataPath);
        
        // 确保data目录存在
        if (!fs.existsSync(dataDir)) {
            fs.mkdirSync(dataDir, { recursive: true });
        }
        
        const newEntry = {
            id: Date.now(),
            name: req.body.name,
            tag: req.body.tag,
            reason: req.body.reason,
            timestamp: new Date().toISOString(),
            status: 'pending'
        };
        
        let blacklist = [];
        if (fs.existsSync(dataPath)) {
            blacklist = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
        }
        
        blacklist.push(newEntry);
        fs.writeFileSync(dataPath, JSON.stringify(blacklist, null, 2));
        
        res.json({ success: true, message: '提交成功，等待审核' });
    } catch (error) {
        console.error('保存黑名单数据失败:', error);
        res.status(500).json({ error: '保存数据失败' });
    }
});

// 管理员审核API
app.post('/api/approve/:id', (req, res) => {
    try {
        const dataPath = path.join(__dirname, 'data', 'blacklist.json');
        if (!fs.existsSync(dataPath)) {
            return res.status(404).json({ error: '数据文件不存在' });
        }
        
        const blacklist = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
        const entry = blacklist.find(item => item.id == req.params.id);
        
        if (!entry) {
            return res.status(404).json({ error: '记录不存在' });
        }
        
        entry.status = req.body.approved ? 'approved' : 'rejected';
        fs.writeFileSync(dataPath, JSON.stringify(blacklist, null, 2));
        
        res.json({ success: true, message: '审核完成' });
    } catch (error) {
        console.error('审核操作失败:', error);
        res.status(500).json({ error: '操作失败' });
    }
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
    console.log(`访问地址: http://localhost:${PORT}`);
    console.log(`如果配置了域名，可以通过 https://coccxy.cn 访问`);
});

// 优雅关闭
process.on('SIGTERM', () => {
    console.log('收到SIGTERM信号，正在关闭服务器...');
    process.exit(0);
});

process.on('SIGINT', () => {
    console.log('收到SIGINT信号，正在关闭服务器...');
    process.exit(0);
}); 